package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.templates.OssTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Slf4j
public class VideoService {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private OssTemplate ossTemplate;

    @Reference
    private VideoApi videoApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发布小视频功能
     *
     * @param videoThumbnail 视屏封面文件
     * @param videoFile      视屏文件
     */
    public void post(MultipartFile videoThumbnail, MultipartFile videoFile) {

        try {
            //1.视屏封面上传到阿里云
            String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
            //2.视频上传到fdfs
            String videoExtension = picUrl.substring(picUrl.lastIndexOf(".") + 1);

            //p1:文件输入流 p2：文件大小 p3:文件后缀名 p4:null
            StorePath storePath = fastFileStorageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), videoExtension, null);
            //文件地址

            String videoUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();

            //3.构建video
            Video video = new Video();
            video.setUserId(UserHolder.getUserId());
            video.setText("探花app");
            video.setPicUrl(picUrl);
            video.setVideoUrl(videoUrl);

            videoApi.add(video);

        } catch (IOException e) {
            //4.调用api保存视频数据到mongodb

            log.error("上传视频失败了", e);
        }

    }

    /**
     * 分页查询小视屏列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult<VideoVo> findPage(Long page, Long pageSize) {
        PageResult pageResult = videoApi.findPage(page, pageSize);
        //获取结果集
        List<Video> videoList = pageResult.getItems();

        List<VideoVo> videoVo = new ArrayList<>();
        if (!CollectionUtils.isEmpty(videoList)) { //结果集没有数据就不需要接着查了

            //获取所有作者的id
            List<Long> longList = videoList.stream().map(Video::getUserId).collect(Collectors.toList());
            //批量查询作者信息
            List<UserInfo> usersInfoLIst = userInfoApi.findByBatchId(longList);
            //把作者信息转成map
            Map<Long, UserInfo> userInfoMap = usersInfoLIst.stream().collect(Collectors.toMap(UserInfo::getId, U -> U));

            //小视频转成vo

            videoVo = videoList.stream().map(video -> {
                VideoVo vo = new VideoVo();
                //   复制视频信息
                BeanUtils.copyProperties(video, vo);
                vo.setId(video.getId().toHexString());//动态id
                vo.setCover(video.getPicUrl()); //封面
                vo.setSignature(video.getText()); //水印

                //复制作者信息
                UserInfo userInfo = userInfoMap.get(video.getUserId());
                BeanUtils.copyProperties(userInfo, vo);

                String key = "follow_user_" + UserHolder.getUserId() + "_" + video.getUserId();
                if (redisTemplate.hasKey(key)) {
                    vo.setHasFocus(1);//1: 关注了
                }
                return vo;
            }).collect(Collectors.toList());


        }
        //构建PageResult
        pageResult.setItems(videoVo);
        return pageResult;
    }

    /**
     * 关注视频作者
     *
     * @param followUserId
     */
    public void focusUser(Long followUserId) {

        //构建FollowUser对象
        FollowUser followUser =new FollowUser();
        followUser.setUserId(UserHolder.getUserId()); //登录用户id
        followUser.setFollowUserId(followUserId); //登录用户关注的用户的id

        //调用api添加
        videoApi.focusUser(followUser);

        //保存到redis
        String key = "follow_user_" + UserHolder.getUserId() + "_" + followUserId;
        redisTemplate.opsForValue().set(key,1);




    }

    /**
     * 取消关注视频作者
     *
     * @param followUserId
     */
    public void userUnFocus(Long followUserId) {
        //构建FollowUser对象(删除条件)
        FollowUser followUser =new FollowUser();
        followUser.setUserId(UserHolder.getUserId()); //登录用户id
        followUser.setFollowUserId(followUserId); //登录用户关注的用户的id

        //调用api删除
        videoApi.removeUser(followUser);

        //删除redis中的数据
        String key = "follow_user_" + UserHolder.getUserId() + "_" + followUserId;
        redisTemplate.delete(key);


    }
}
